package com.akk.platform.manage;

import com.akk.common.enums.Enums;
import com.akk.module.avs.entity.AvsCustomer;
import com.akk.module.avs.entity.AvsPayOrder;
import com.akk.module.avs.model.response.AvsIncreRecordRes;
import com.akk.module.avs.model.response.AvsPayOrderRecordRes;
import com.akk.module.avs.model.response.AvsPayOrderSummaryRes;
import com.akk.module.avs.service.AvsCustomerService;
import com.akk.module.avs.service.AvsPayOrderService;
import com.akk.utils.PageUtils;
import com.akk.utils.Query;
import com.akk.utils.RestResponse;
import com.akk.utils.WriteExcel;
import com.akk.utils.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/platform/manage/payRecord")
public class AvsPayRecord {

    @Autowired
    private AvsPayOrderService orderService;

    @Autowired
    private AvsCustomerService customerService;

    @Autowired
    private WriteExcel writeExcel;

    @RequestMapping(value = "/list")
    @RequiresPermissions("platform:manage:payrecord:list")
    public RestResponse list(@Valid Query query){
        PageHelper.startPage(query.getPage(),query.getLimit());
        List<AvsPayOrderRecordRes> orders = orderService.findByParams(query.getSearch());
        return RestResponse.build(PageUtils.buildPage(orders,(int) new PageInfo<>(orders).getTotal(),query));
    }

    @RequestMapping(value = "/info/{orderId}")
    @RequiresPermissions("platform:manage:payrecord:info")
    public RestResponse info(@PathVariable String orderId){
        AvsPayOrderRecordRes order = orderService.queryInfoById(orderId);
        AvsCustomer customer = customerService.findByCustomerId(order.getPayerId());
        Map result = new HashMap();
        result.put("order",order);
        result.put("customer",customer);
        return RestResponse.build(result);
    }

    @RequestMapping(value = "/summary")
    @RequiresPermissions("platform:manage:payrecord:summary")
    public RestResponse summary(){
        // 未支付
        AvsPayOrderSummaryRes noPayCount = orderService.countByStatus(Enums.OrderStatusEnum.NO_PAYED.getValue());
        // 退款中
        AvsPayOrderSummaryRes refundingCount = orderService.countByStatus(Enums.OrderStatusEnum.REFUNDING.getValue());
        // 退款
        AvsPayOrderSummaryRes refundCount = orderService.countByStatus(Enums.OrderStatusEnum.REFUND.getValue());
        // 处理中
        AvsPayOrderSummaryRes doingCount = orderService.countByStatus(Enums.OrderStatusEnum.DOING.getValue());
        // 失败
        AvsPayOrderSummaryRes failedCount = orderService.countByStatus(Enums.OrderStatusEnum.FAILED.getValue());
        // 支付成功
        AvsPayOrderSummaryRes paySuccessCount = orderService.countByStatus(Enums.OrderStatusEnum.SUCCESS_PAYED.getValue());
        // 提现成功
        AvsPayOrderSummaryRes depositSuccessCount = orderService.countByStatus(Enums.OrderStatusEnum.SUCCESS_DEPOSIT.getValue());
        // 缴费成功
        AvsPayOrderSummaryRes vipSuccessCount = orderService.countByStatus(Enums.OrderStatusEnum.VIP_SUCCESS.getValue());
        // 奖励成功
        AvsPayOrderSummaryRes rewaaedCount = orderService.countByStatus(Enums.OrderStatusEnum.SUCCESS_REWAARD.getValue());
        Map result = new HashMap();
        result.put("noPayCount",noPayCount);
        result.put("refundingCount",refundingCount);
        result.put("refundCount",refundCount);
        result.put("doingCount",doingCount);
        result.put("failedCount",failedCount);
        result.put("paySuccessCount",paySuccessCount);
        result.put("depositSuccessCount",depositSuccessCount);
        result.put("vipSuccessCount",vipSuccessCount);
        result.put("rewaaedCount",rewaaedCount);
        return RestResponse.build(result);
    }

    @GetMapping(value = "/download")
    @RequiresPermissions("platform:manage:payrecord:download")
    public void download(Query query, HttpServletResponse response){
        List<AvsPayOrderRecordRes> orders = orderService.findByParams(query.getSearch());
        String title = "极速收款订单记录";
        downloadExcelFile(title,orders,response);
    }

    //Web 导出excel
    public void downloadExcelFile(String title, List<AvsPayOrderRecordRes> datas, HttpServletResponse response){
        try {
            String[] titles = {"用户名","手机号","订单编号","交易银行","交易卡号","订单金额","服务费","网关成本","利润","使用通道","出款金额","结算银行","结算卡号","订单状态","刷卡时间"};
            String[] columns = {"username","phone","orderNum","payBank","payCardNo","amountTotal","serviceCost","gatewayCost","profit","accessName","realAmount","collecBank","cashCardNo","status","createDate"};
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            String jsonStr = gson.toJson(datas);
            Map<String,Map<String,String>> replace = new HashMap<>();
            Map<String,String> values = new HashMap<>();
            values.put("1.0","未付款");
            values.put("2.0","已取消");
            values.put("3.0","已退款");
            values.put("4.0","处理中");
            values.put("6.0","提现失败");
            values.put("7.0","支付成功");
            values.put("8.0","缴费成功");
            values.put("9.0","奖励成功");
            replace.put("status",values);
            Map<Integer,Integer> columnWidth = new HashMap<>();
            columnWidth.put(0,20);
            columnWidth.put(1,20);
            columnWidth.put(2,30);
            columnWidth.put(3,20);
            columnWidth.put(4,30);
            columnWidth.put(5,20);
            columnWidth.put(6,20);
            columnWidth.put(7,20);
            columnWidth.put(8,20);
            columnWidth.put(9,20);
            columnWidth.put(10,20);
            columnWidth.put(11,20);
            columnWidth.put(12,30);
            columnWidth.put(13,20);
            columnWidth.put(14,30);
            File file = writeExcel.exportExcel(title,jsonStr,titles,replace,columnWidth,columns);
            InputStream is = new FileInputStream(file);
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String((title + ".xls").getBytes(), "ISO-8859-1"));
            ServletOutputStream outputStream = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(outputStream);
            byte[] buff = new byte[8192];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            is.close();
            bis.close();
            bos.close();
            outputStream.flush();
            outputStream.close();
            file.delete();
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("导出Excel失败");
        }
    }

}
